package com.endoc.btmodule;

import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.util.Log;
import java.util.UUID;
import java.util.logging.Logger;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.Options;
import cn.com.heaton.blelibrary.ble.callback.BleConnectCallback;
import cn.com.heaton.blelibrary.ble.callback.BleMtuCallback;
import cn.com.heaton.blelibrary.ble.callback.BleNotifyCallback;
import cn.com.heaton.blelibrary.ble.callback.BleScanCallback;
import cn.com.heaton.blelibrary.ble.callback.BleWriteCallback;
import cn.com.heaton.blelibrary.ble.model.BleDevice;

public class BleModel {
    static String TAG ="BleTool";
    public static void initBle(Context context, Options options, Ble.InitCallback callback){
        Ble.getInstance().init(context,options,callback);
    }

    public  void initBle(Context context){
        //Ble.getInstance().init(context,options,callback);
        Ble.options().setLogTAG("agingTool")
                //.setLogBleExceptions(true)//设置是否输出打印蓝牙日志（非正式打包请设置为true，以便于调试）
                .setThrowBleException(true)//设置是否抛出蓝牙异常
                .setAutoConnect(true)//设置是否自动连接
                .setConnectFailedRetryCount(3)//连接失败重试时间
                .setConnectTimeout(10 * 1000)//设置连接超时时长（默认10*1000 ms）
                .setScanPeriod(10*1000)//设置扫描时长（默认10*1000 ms）
                .setMaxConnectNum(5)//默认是7
                .setUuidService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"))//主服务的uuid
                .setUuidWriteCha(UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb"))//可写特征的uuid
                .create(context);
    }
    public  IBleCallBack iBleCallBack;

    public  void setMTU(BleDevice device,int mtuLen){
        Ble.getInstance().setMTU(device.getBleAddress(), mtuLen, new BleMtuCallback<BleDevice>() {
            @Override
            public void onMtuChanged(BleDevice device, int mtu, int status) {
                super.onMtuChanged(device, mtu, status);
                iBleCallBack.onMtuChanged(device, mtu, status);
            }
        });
    }
    //注册回调接口
    public   void setIBleCallBack(IBleCallBack iBleCallBack) {
        this.iBleCallBack = iBleCallBack;
    }

    public  void scanBle(){

        Ble.getInstance().startScan(new BleScanCallback<BleDevice>() {
            @Override
            public void onLeScan(BleDevice device, int rssi, byte[] scanRecord) {
                iBleCallBack.onLeScan(device,rssi,scanRecord);
            }
        });
    }

    public  void connectBle( BleDevice device){
        Ble.getInstance().connect(device, new BleConnectCallback<BleDevice>() {
            @Override
            public void onConnectionChanged(BleDevice device) {
                Log.d(TAG,device.getBleName()+"连接状态"+device.isConnected()+" 当前回调的hash值"+this.hashCode());
                iBleCallBack.onConnectionChanged(device);

            }

            @Override
            public void onReady(BleDevice device) {
                super.onReady(device);
                iBleCallBack.onReady(device);
            }
        });
    }




    public  void enableNotify(BleDevice device){
        //设置读写监听
        Ble.getInstance().enableNotify(device, true, new BleNotifyCallback<BleDevice>() {
            @Override
            public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) {
                iBleCallBack.receiveData(device,characteristic);
                //Log.d(TAG,"收到硬件数据");
            }
        });
    }

    public  void enableUUIDNotify(BleDevice device,UUID serviceUUID, UUID characteristicUUID){
        //设置读写监听
       Ble.getInstance().enableNotifyByUuid(device,true,serviceUUID,characteristicUUID, new BleNotifyCallback<BleDevice>() {
           @Override
           public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) {
               iBleCallBack.receiveData(device,characteristic);
           }
       });
    }

    public  void disconnectBle(BleDevice device){
        Ble.getInstance().disconnect(device);
    }

    public  void writeData(BleDevice device,byte [] data,UUID serviceUUID, UUID writeCharacteristicUUID){
        if(!device.isConnected()){
            //Log.d(TAG,"没有连接,请先连接设备");
            return;
        }
        Ble.getInstance().writeByUuid(device, data, serviceUUID, writeCharacteristicUUID, new BleWriteCallback<BleDevice>() {
            @Override
            public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic characteristic) {
                String sendData = DataUtils.bytesToHexString(characteristic.getValue(), characteristic.getValue().length);
                String deviceName =device.getBleName();
                //Log.d(TAG,"write success:"+deviceName+"   data:"+sendData);
                iBleCallBack.onWriteSuccess(device,characteristic);
            }

            @Override
            public void onWriteFailed(BleDevice device, int failedCode) {
                super.onWriteFailed(device, failedCode);
                iBleCallBack.onWriteFailed(device,failedCode);
            }
        });
    }

    public  void writeData(BleDevice device,byte data[]){
        //Log.d(TAG,"写入数据"+DataUtils.bytesToHexString(data,data.length));
        if(!device.isConnected()){
            //Log.d(TAG,"没有连接,请先连接设备");
            return;
        }
        Ble.getInstance().write(device, data, new BleWriteCallback<BleDevice>() {
            @Override
            public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic characteristic) {
                String sendData = DataUtils.bytesToHexString(characteristic.getValue(), characteristic.getValue().length);
                String deviceName =device.getBleName();
                //Log.d(TAG,"write success:"+deviceName+"   data:"+sendData);
                iBleCallBack.onWriteSuccess(device,characteristic);
            }

            @Override
            public void onWriteFailed(BleDevice device, int failedCode) {
                super.onWriteFailed(device, failedCode);
                iBleCallBack.onWriteFailed(device,failedCode);
            }
        });

    }

}
